package com.db.stexchem.server;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.db.stexchem.exceptions.BadAuthenticationException;
import com.db.stexchem.message.LoginRequest;

public class LoginService {
  
  private final Logger                                   logger = LoggerFactory
                                                                    .getLogger(LoginService.class);
  private final Map<String, String>                      passwordStorage;
  private final ConcurrentHashMap<String, ClientSession> activeSessions;
  
  public LoginService(Map<String, String> passwordStorage,
      ConcurrentHashMap<String, ClientSession> activeSessions) {
    this.passwordStorage = passwordStorage;
    this.activeSessions = activeSessions;
  }
  
  public String login(final LoginRequest request,
      final ClientSession clientSession) throws BadAuthenticationException {
    String login = request.getLoginName();
    logger.trace("checking authentification for client '{}' ...", login);
    String password = request.getPassword();
    if (password == null) {
      throw new BadAuthenticationException("password must be a non-null value");
    } else if (passwordStorage.get(login) == null) {
      throw new BadAuthenticationException("client with login '" + login
          + "' doesn't exist");
    } else if (!password.equals(passwordStorage.get(login))) {
      throw new BadAuthenticationException("wrong password: '" + password
          + "' for login: '" + login + "'");
    } else if (activeSessions.putIfAbsent(login, clientSession) != null) {
      throw new BadAuthenticationException("client with login '" + login
          + "' is already connected");
    } else {
      logger.trace("client '{}' has been successfully authentificated", login);
      return login;
    }
  }
  
  public void logout(final String login) {
    if (login != null) {
      logger.trace("logout client '{}'", login);
      activeSessions.remove(login);
    }
  }
}
